package com.zcsy.manage.web.main;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.model.RequestConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.util.JExcelReportUtil;
import com.zcsy.commons.util.JFreeChartUtil;
import com.zcsy.commons.util.MailUtil;
import com.zcsy.commons.util.XlsImportUtils;
import com.zcsy.manage.model.base.CellInfo;
import com.zcsy.manage.model.system.Menu;
import com.zcsy.manage.model.system.Role;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.service.base.ICellHouseService;
import com.zcsy.manage.service.base.ICellInfoService;
import com.zcsy.manage.service.base.IShopInfoService;
import com.zcsy.manage.service.common.CommonService;
import com.zcsy.manage.service.system.ILogService;
import com.zcsy.manage.service.system.IMenuService;
import com.zcsy.manage.service.system.IRoleService;
import com.zcsy.manage.web.common.LogUtils;

/**
 * 
 * @Title: MainController.java @Package： com.zcsy.manage.web.main
 * @Description: 工程入口方法
 * @author chensf 735569870@qq.com
 * @Copyright: 2015 武汉中财数元信息技术有限公司 All rights reserved.
 * @date 2016年1月8日
 * @version 1.0
 * @see JDK1.7.0_75
 * @since
 */
@Controller
public class MainController {

    @Autowired
    private IMenuService menuService;

    @Autowired
    ILogService logService;

    @Autowired
    IRoleService roleService;

    @Autowired
    private ICellInfoService cellInfoService;

    @Autowired
    private IShopInfoService shopInfoService;

    @Autowired
    private ICellHouseService cellHouseService;
    
    /**
     * 
     * @Description <br>
     *              链接到登录页面
     * @param model
     * @param req
     *            请求
     * @param res
     *            响应
     * @author chensf 735569870@qq.com
     * @date 2016年1月8日
     * @see
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    public String toLogin(Model model, HttpServletRequest req, HttpServletResponse res) {

        return "login";
    }

    /**
     * 二三级菜单区域加载失败
     * 
     * @param model
     *            对象
     * @param req
     *            请求
     * @param res
     *            响应
     * @param menuId
     *            菜单ID
     * @return
     */
    @RequestMapping(value = "leftError", method = RequestMethod.GET)
    public String leftError(Model model, HttpServletRequest req, HttpServletResponse res, int menuId) {
        model.addAttribute("menuId", menuId);
        return "error/leftError";
    }

    /**
     * 内容区域加载失败
     * 
     * @param model
     *            对象
     * @param req
     *            请求
     * @param res
     *            响应
     * @param url
     *            内容链接
     * @return
     */
    @RequestMapping(value = "contentError", method = RequestMethod.GET)
    public String contentError(Model model, HttpServletRequest req, HttpServletResponse res, String url) {
        model.addAttribute("url", url);
        return "error/contentError";
    }

    /**
     * 主页面刷新
     * 
     * @param req
     *            请求
     * @param res
     *            响应
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "main", method = RequestMethod.GET)
    public String main(HttpServletRequest req, HttpServletResponse res) throws Exception {
        // 获取当前用户
        User user = CommonService.getSessionUser();

        if (user == null) {
            res.sendRedirect(req.getContextPath() + "/");
            return null;
        }

        return "main";
    }

    /**
     * 二三级菜单区域刷新
     * 
     * @param menuId
     *            一级菜单ID
     * @param req
     *            请求
     * @param res
     *            响应
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "left", method = RequestMethod.GET)
    public String left(String menuId, HttpServletRequest req, HttpServletResponse res, String cellId) throws Exception {
        // 获取session
        HttpSession session = req.getSession();

        // 获取当前用户
        User user = CommonService.getSessionUser();

        if (user == null) {
            res.sendRedirect(req.getContextPath() + "/");
            return null;
        }

        // 获取菜单
        List<Menu> menus = CommonService.getSessionMenus();
        List<Menu> secondMenus = null;
        for (Menu menu : menus) {
            if (menu.getId().equals(menuId)) {
                secondMenus = menu.getSubMenus();
                break;
            }
        }

        session.setAttribute("secondMenus", secondMenus);

        // 在左边菜单添加商户申请的数目
        if (StringUtils.isNotEmpty(cellId)) {
            Integer numberOfApplying = shopInfoService.countApply(cellId);
            session.setAttribute("numberOfApplying", numberOfApplying);

            Menu menu = menuService.queryByLocationURL(RequestConstants.shopApplyUrl);
            String shopApplyId = menu.getId();
            session.setAttribute("shopApplyId", shopApplyId);
        }
        
        // 在左边菜单添加业主申请的数目
        if (StringUtils.isNotEmpty(cellId)) {
            Integer numberOfOwnerApply = cellHouseService.countApply(cellId);
            session.setAttribute("numberOfOwnerApplying", numberOfOwnerApply);

            Menu menuForOwner = menuService.queryByLocationURL(RequestConstants.ownerApplyUrl);
            String ownerApplyId = menuForOwner.getId();
            session.setAttribute("ownerApplyId", ownerApplyId);
        }
        return "left";
    }

    /**
     * 获取一级菜单下第一个内容菜单刷新显示
     * 
     * @param menuId
     *            一级菜单ID
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "content", method = RequestMethod.GET)
    @ResponseBody
    public RequestJson content(String menuId) throws Exception {
        RequestJson json = new RequestJson();
        try {

            // 从缓存中获取菜单
            List<Menu> menus = CommonService.getSessionMenus();
            List<Menu> secondMenus = null;
            for (Menu menu : menus) {
                if (menu.getId().equals(menuId)) {
                    secondMenus = menu.getSubMenus();
                    break;
                }
            }

            Menu homeMenu = menuService.getFirstAvailableMenus(secondMenus);
            json.setObj(homeMenu);
        } catch (Exception e) {
            json.setSuccess(false);
        }
        return json;
    }

    @RequestMapping(value = "changeCell", method = RequestMethod.GET)
    @ResponseBody
    public RequestJson changeCell(String cellId, Model model, HttpServletRequest request) throws Exception {
        RequestJson json = new RequestJson();
        try {
            // 获取当前用户
            User user = CommonService.getSessionUser();
            // 获取当前小区信息
            CellInfo cellInfo = cellInfoService.selectByPrimaryKey(cellId);
            if (user.getUserType() != Constants.ADMIN_TYPE) {
                if (!menuService.updateUserFirstMenuBycell(user, Constants.SYSTEM_OPERATION_WEB, cellId)) {
                    json.setSuccess(false);
                    json.setMsg("您没有该小区的管理权限，请联系管理员");
                } else {
                    user.setCurrentCell(cellInfo);
                    CommonService.setSessionUser(user);
                    CommonService.setSessionMenus(user.getCellMenus());
                    LogUtils.insertLog("用户切换小区", user.getId(), request);
                }
            } else {
                if (!menuService.updateAdminUserFirstMenu(user, Constants.SYSTEM_OPERATION_WEB, cellId)) {
                    json.setSuccess(false);
                    json.setMsg("您没有该小区的管理权限，请联系管理员");
                } else {
                    user.setCurrentCell(cellInfo);
                    CommonService.setSessionUser(user);
                    CommonService.setSessionMenus(user.getCellMenus());
                    LogUtils.insertLog("用户切换小区", user.getId(), request);
                }
            }
        } catch (Exception e) {
            json.setSuccess(false);
            json.setMsg("切换失败");
        }
        return json;
    }

    @RequestMapping(value = "searchCell", method = RequestMethod.GET)
    @ResponseBody
    public RequestJson searchCell(String cellName) throws Exception {
        RequestJson json = new RequestJson();
        try {
            // 获取当前用户
            User user = CommonService.getSessionUser();
            if (StringUtils.isEmpty(cellName)) {
                json.setObj(user.getCellInfos());
                return json;
            }

            List<CellInfo> cells = new ArrayList<CellInfo>();
            if (user.getCellInfos() != null && user.getCellInfos().size() > 0) {
                for (CellInfo item : user.getCellInfos()) {
                    if (item.getCellName().contains(cellName)) {
                        cells.add(item);
                    }
                }
            }

            json.setObj(cells);
            return json;
        } catch (Exception e) {
            json.setSuccess(false);
        }
        return json;
    }

    /**
     * 
     * @Description <br>
     *              测试发送邮件方法
     * @param content
     *            邮件正文
     * @param subject
     *            邮件主题
     * @param req
     *            请求
     * @return 发送结果
     * @author chensf 735569870@qq.com
     * @date 2016年1月11日
     * @see
     */
    @RequestMapping(value = "sendEmail", method = RequestMethod.GET)
    @ResponseBody
    public RequestJson saveOrUpdateEmail(String content, String subject, HttpServletRequest request) {

        boolean sendResult = false;
        RequestJson result = new RequestJson();
        User user = (User) request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        try {

            // 邮箱数组，只能用次方式获取参数
            String[] emails = request.getParameterValues("emails");

            sendResult = MailUtil.sendEmail(emails, content, subject);

            if (sendResult) {
                result.setMsg("发送成功");// 保存状态到前端
                result.setSuccess(true);
                LogUtils.insertLog("用户发送邮件", user.getId(), request);
            } else {
                result.setSuccess(false);
                result.setMsg("发送失败");
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("操作失败");
        }
        return result;
    }

    /**
     * 
     * @Description <br>
     *              柱状图报表测试方法
     * @param model
     * @param req
     *            请求
     * @return 页面路径
     * @author chensf 735569870@qq.com
     * @date 2016年1月12日
     * @see
     */
    @RequestMapping(value = "getBarReport", method = RequestMethod.GET)
    public String getBarReport(Model model, HttpServletRequest req) {

        // 获取session
        HttpSession session = req.getSession();

        ArrayList<ArrayList<String>> dataList = new ArrayList<ArrayList<String>>();

        List<Map<String, Object>> logReports = logService.getReportByDate();

        // 将要生成报表的数据放到list集合
        for (Map<String, Object> item : logReports) {

            ArrayList<String> list = new ArrayList<String>();

            list.add(item.get("amount").toString());
            list.add(item.get("logcontent").toString());
            list.add(item.get("date").toString().substring(5));

            dataList.add(list);
        }

        // 报表标题
        String title = "日志统计";
        // x轴标题
        String xTitle = "操作类型";
        // y轴标题
        String yTitle = "数量";
        // 报表是否垂直显示
        boolean isVertical = true;
        // 是否使用legend
        boolean useLegend = true;
        boolean useTooltip = true;
        boolean useUrl = false;
        int width = 1500;
        int height = 400;
        // 是否使用3D
        boolean is3D = false;
        // 是否显示值
        boolean showValue = true;

        Map<String, String> map = JFreeChartUtil.createBarReport(dataList, title, xTitle, yTitle, isVertical, useLegend,
                useTooltip, useUrl, width, height, is3D, showValue, session, req);

        model.addAttribute("graphURL", map.get("graphURL"));
        model.addAttribute("filename", map.get("filename"));

        return "system/report/logReport";

    }

    /**
     * @Description 附件管理页面<br>
     * @param model
     *            视图对象
     * @param req
     *            请求对象
     * @return 页面地址
     * @author tanhuatang 786468449@qq.com
     * @date 2016年1月15日
     * @see
     */
    @RequestMapping(value = "filePage", method = RequestMethod.GET)
    public String filePage(Model model, HttpServletRequest req) {
        return "system/uploader/filePage";
    }

    /**
     * 
     * @Description <br>
     *              柱状图报表测试方法
     * @param model
     * @param req
     *            请求
     * @return 页面路径
     * @author chensf 735569870@qq.com
     * @date 2016年1月12日
     * @see
     */
    @RequestMapping(value = "getPieReport", method = RequestMethod.GET)
    public String getPieReport(Model model, HttpServletRequest req) {

        // 获取session
        HttpSession session = req.getSession();

        ArrayList<ArrayList<String>> dataList = new ArrayList<ArrayList<String>>();

        List<Map<String, Object>> logReports = logService.getReport();

        // 将要生成报表的数据放到list集合
        for (Map<String, Object> item : logReports) {

            ArrayList<String> list = new ArrayList<String>();

            list.add(item.get("logcontent").toString());
            list.add(item.get("amount").toString());

            dataList.add(list);
        }

        // 报表标题
        String title = "日志统计";

        // 是否使用legend
        boolean useLegend = true;
        boolean useTooltip = true;
        boolean useUrl = false;
        int width = 700;
        int height = 400;
        // 是否使用3D
        boolean is3D = true;
        // 是否3D透明
        boolean set3Dstyle = false;
        // s是否圆形
        boolean isCircular = false;
        // 是否显示百分比
        boolean showPercent = true;

        Map<String, String> map = JFreeChartUtil.createPieChart(dataList, title, set3Dstyle, isCircular, useLegend,
                useTooltip, useUrl, width, height, is3D, showPercent, session, req);

        model.addAttribute("graphURL", map.get("graphURL"));
        model.addAttribute("filename", map.get("filename"));

        return "system/report/logReport";

    }

    /**
     * 
     * @Description <br>
     *              折线图报表测试方法
     * @param model
     * @param req
     *            请求
     * @return 页面路径
     * @author chensf 735569870@qq.com
     * @date 2016年1月14日
     * @see
     */
    @RequestMapping(value = "getLineReport", method = RequestMethod.GET)
    public String getLineReport(Model model, HttpServletRequest req) {
        // 报表标题
        String title = "日志统计";

        // x轴标题
        String xTitle = "";
        // y轴标题
        String yTitle = "数量";

        // 获取session
        HttpSession session = req.getSession();

        ArrayList<ArrayList<String>> dataList = new ArrayList<ArrayList<String>>();

        // 按天统计方式
        /*
         * List<Map<String, Object>> logReports = logService.getReportByDate();
         * 
         * Set<String> sets = new HashSet<String>(); //将要生成报表的数据放到list集合
         * for(Map<String, Object> item : logReports){
         * 
         * sets.add(item.get("date").toString().substring(0,4));
         * 
         * ArrayList<String> list = new ArrayList<String>();
         * 
         * list.add(item.get("amount").toString());
         * list.add(item.get("logcontent").toString());
         * list.add(item.get("date").toString().substring(5));
         * 
         * dataList.add(list); }
         * 
         * for(String set : sets){ if("".equals(xTitle)){
         * 
         * xTitle = set; }else{
         * 
         * xTitle += "-" + set; } }
         */

        // 按周统计方式
        /*
         * List<Map<String, Object>> logReports = logService.getReportByWeek();
         * 
         * //将要生成报表的数据放到list集合 for(Map<String, Object> item : logReports){
         * 
         * ArrayList<String> list = new ArrayList<String>();
         * 
         * list.add(item.get("amount").toString());
         * list.add(item.get("logcontent").toString());
         * list.add(item.get("year").toString() + "第" +
         * item.get("week").toString() + "周");
         * 
         * dataList.add(list); }
         */

        // 按月统计方式
        List<Map<String, Object>> logReports = logService.getReportByMonth();

        // 将要生成报表的数据放到list集合
        for (Map<String, Object> item : logReports) {

            ArrayList<String> list = new ArrayList<String>();

            list.add(item.get("amount").toString());
            list.add(item.get("logcontent").toString());
            list.add(item.get("year").toString() + "年" + item.get("month").toString() + "月");

            dataList.add(list);
        }

        // 是否使用legend
        boolean useLegend = true;
        boolean useTooltip = true;
        boolean useUrl = false;
        int width = 1000;
        int height = 500;
        // 是否使用3D
        boolean is3D = false;
        // 是否显示值
        boolean showValue = false;

        Map<String, String> map = JFreeChartUtil.createLineReport(dataList, title, xTitle, yTitle, useLegend,
                useTooltip, useUrl, width, height, is3D, showValue, session, req);

        model.addAttribute("graphURL", map.get("graphURL"));
        model.addAttribute("filename", map.get("filename"));

        return "system/report/logReport";

    }

    /**
     * 
     * @Description <br>
     *              导出excel测试方法
     * @param request
     *            请求
     * @param response
     *            响应
     * @author chensf 735569870@qq.com
     * @date 2016年1月15日
     * @see
     */
    @RequestMapping(value = "exportLog", method = RequestMethod.GET)
    @ResponseBody
    public void exportLog(HttpServletRequest request, HttpServletResponse response) {

        List<Map<String, Object>> logReports = logService.getReportByMonth();
        ArrayList<ArrayList<String>> dataList = new ArrayList<ArrayList<String>>();

        for (Map<String, Object> log : logReports) {
            ArrayList<String> reportList = new ArrayList<String>();

            reportList.add(log.get("year").toString() + "年" + log.get("month").toString() + "月");
            reportList.add(log.get("logcontent").toString());
            reportList.add(log.get("amount").toString());

            dataList.add(reportList);
        }

        // 导出标题列
        String[] rows = new String[] { "日期", "操作内容", "数量" };
        // 导出excel文件每列宽度
        int[] style = new int[] { 20, 20, 20 };
        // Excel文件sheet名称
        String sheetName = "日志报表统计";

        try {
            ServletOutputStream fout = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "filename=order_report.xls");
            JExcelReportUtil jexcelOutStream = new JExcelReportUtil();
            jexcelOutStream.excelreport(sheetName, dataList, rows, fout, style);
            fout.flush();
            fout.close();
        } catch (Exception e) {
        }

    }

    /**
     * 
     * @Description <br>
     *              excel导入测试方法
     * @param request
     *            请求
     * @param response
     *            响应
     * @return 导入结果
     * @author chensf 735569870@qq.com
     * @date 2016年1月15日
     * @see
     */
    @RequestMapping(value = "importXls", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson importXls(HttpServletRequest request, HttpServletResponse response) {

        RequestJson json = new RequestJson();

        // 文件输入流
        InputStream inputStream = null;

        if (ServletFileUpload.isMultipartContent(request)) {
            try {
                // 转换为文件请求
                MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
                // 获取多文件
                Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();

                // 文件遍历上传
                for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                    MultipartFile file = entity.getValue();
                    if (file != null && file.getSize() > 0) {

                        // 获取文件输入流
                        inputStream = file.getInputStream();

                        List<List> list = XlsImportUtils.parseXlsToString(inputStream, 2, 1, 0);
                        if (list != null && !list.isEmpty()) {

                            for (List item : list) {

                                Role role = new Role();
                                role.setRoleName(item.get(0).toString());
                                role.setDescrip(item.get(1).toString());

                                roleService.insert(role);
                            }
                            json.setSuccess(true);
                        } else {
                            json.setSuccess(false);
                            json.setMsg("文件数据错误！");
                        }
                    }
                }
            } catch (Exception e) {
                json.setSuccess(false);
                json.setMsg("操作异常！");
            } finally {

                if (inputStream != null) {

                    try {
                        inputStream.close();
                    } catch (IOException e) {
                    }
                }
            }
        }

        return json;
    }

}
